package com.sanhuo.security.controller;

import com.sanhuo.security.UserVo;
import com.sanhuo.security.global.Response;
import com.sanhuo.security.global.ResponseEnum;
import com.sanhuo.security.uitls.UserHolder;
import com.sanhuo.security.uitls.VerifyCodeHolder;
import com.sanhuo.utils.VerifyCode;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class SecurityController {

    /**
     * 登录
     *
     * @return
     * @throws IllegalAccessException
     */
    @CrossOrigin
    @RequestMapping("/login")
    public Response login() {
//        UserToken userToken = userTokenService.updateToken(bo.getId());
        UserVo userVo = UserHolder.user();
        return new Response(ResponseEnum.LOGIN_SUCCESS.getCode(), ResponseEnum.LOGIN_SUCCESS.getMsg(), userVo);
    }

    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("verifyCode")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取生成验证码的对象
        VerifyCode vrCode = new VerifyCode();
        //获取验证码的图片
        BufferedImage image = vrCode.getImage();
        //获取验证码的文本
        String vrCodeText = vrCode.getText();
        //从http请求体request中获取ip地址为键,验证码的文本为值存放在内存永久区的map中
        VerifyCodeHolder.put(request, vrCodeText);
        //获取响应的输出流,将验证码转换为二进制流输出到响应体里
        VerifyCode.output(image, response.getOutputStream());
//        System.out.println("verifyCode:" + vrCodeText);
    }
}
